﻿/*
创建人：zhangrj
日期：2023-07-27
描述：转工计划排产转出确认js
*/
var page = {
  pageTotal: 0,
  pageSize: 20,
  pageNumber: 1,
  apsPlanDetailDatas: [], //编辑弹窗选择的主数据
  rootPath: getRootPath(), //网站根路径
  url: getRootPath() + "/Ashx/ApsHandler/ApsPlanConfirmHandler.ashx",
  //初始化页面
  init: function () {
    page.bind();
    page.initPage();
    customizedEasyuiPagination('pp'); //定制化分页
  },
  //页面事件绑定
  bind: function () {
    //排产列表加载
    $("#gdApsPlanInfo").datagrid({
      onLoadSuccess: function (data) {
        $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
          total: page.pageTotal,
          pageSize: page.pageSize,
          pageNumber: page.pageNumber
        });
        customizedEasyuiPagination('pp'); //定制化分页
      },
      columns: [[
        { field: 'ck', title: '选择', checkbox: true },
        { field: 'MFGORDERNAME', title: '订单号', width: 150 },
        { field: 'CONTAINERNAME', title: '批次号', width: 150 },
        { field: 'DESCRIPTION', title: '零件名称', width: 150 },
        { field: 'WORKFLOWINFO', title: '工艺版次', width: 150 },
        { field: 'NOWWORKFLOWSTEPNAME', title: '当前序', width: 120 },
        { field: 'WORKFLOWSTEPNAME', title: '转工序', width: 120 },
        { field: 'APSQTY', title: '计划数', width: 60 },
        { field: 'MAINFACTORYNAME', title: '主制工厂', width: 120 },
        { field: 'TEAMNAME', title: '件号主制单元', width: 100 },
        { field: 'ASSISFACTORYNAME', title: '承制工厂', width: 120 },
        { field: 'CONTAINERTYPENAME', title: '批次类型', width: 100 },
        { field: 'APSTYPENAME', title: '排产策略', width: 80 },
        {
          field: 'CREATEDATE', title: '计划生成时间', width: 100,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD');
            }
          }
        },
        {
          field: 'STARTTIME', title: '计划开始时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        {
          field: 'ENDTIME', title: '计划结束时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        { field: 'CONFIRMEMP', title: '转出人', width: 100 },
        {
          field: 'CONFIRMDATE', title: '转出时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        {
          field: 'SHIPRECPLANSTARTDATE', title: '反馈开始时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        {
          field: 'SHIPRECPLANENDDATE', title: '反馈结束时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        { field: 'RECEIVEEMP', title: '接收人', width: 100 },
        {
          field: 'SHIPRECEIVEDATE', title: '接收时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        { field: 'STATUSNAME', title: '确认状态', width: 60 }
      ]]
    });
    //查询按钮
    $('#btnSearch').on("click", function () {
      page.clearPage(false, true, true);
      page.pageNumber = 1;
      page.searchData();
    });
    //分页事件
    $('#pp').pagination({
      onSelectPage: function (pageNumber, pageSize) {
        page.clearPage(false, true, true);
        customizedEasyuiPagination('pp'); //定制化分页
        page.pageSize = pageSize; page.pageNumber = pageNumber;
        page.searchData();
      }
    });
    //绑定分页go按钮
    $('#pageGo').on("click", function () {
      page.clearPage(false, true, true);
      var pageNumber = $(this).parents('tr').find('.pagination-num').val();
      page.pageNumber = pageNumber;
      page.searchData();
    });
    //清除按钮
    $('#btnReset').on("click", function () {
      page.clearPage(true, true, true);
      page.pageNumber = 1; page.pageTotal = 0
      $('#pp').pagination('refresh', {
        total: page.pageTotal,
        pageSize: page.pageSize,
        pageNumber: page.pageNumber
      });
    });
    //状态下拉选择
    $('#selStatus').combobox({
      onSelect: function (record) {
        clearEasyuiDataGrid("gdApsPlanInfo");
        switch (record.value) {
          case "0":
            $('#selIsFeedback').combobox("setValue", "0");
            $("#btnTransferOut").show();
            $("#btnEditAps").show();
            $("#divIsFeedback").hide();
            break;
          case "2":
            $('#selIsFeedback').combobox("setValue", "0");
            $("#btnTransferOut").hide();
            $("#btnEditAps").show();
            $("#divIsFeedback").show();
            break;
          case "3":
            $('#selIsFeedback').combobox("setValue", "0");
            $("#btnTransferOut").hide();
            $("#btnEditAps").hide();
            $("#divIsFeedback").hide();
            break;
          default:
        }
      }
    });
    //是否反馈下拉选择
    $('#selIsFeedback').combobox({
      onSelect: function (record) {
        clearEasyuiDataGrid("gdApsPlanInfo");
        switch (record.value) {
          case "0":
            $("#btnReceive").hide();
            break;
          case "1":
            $("#btnReceive").show();
            break;
          default:
        }
      }
    });
    //扫描批次事件
    $('#txtScanContainer').textbox({
      onChange: function (n, o) {
        page.pageNumber = 1;
        page.searchData();
      }
    });
    //扫描批次事件
    $('#txtScanOrder').textbox({
      onChange: function (n, o) {
        page.pageNumber = 1;
        page.searchData();
      }
    });
    //转出
    $('#btnTransferOut').on("click", function () {
      page.clearPage(false, false, true);
      page.saveOut();
    });
    //确认调整
    $('#btnReceive').on("click", function () {
      page.clearPage(false, false, true);
      page.saveReceive();
    });
    //编辑排产数据
    $("#btnEditAps").on("click", function () {
      page.clearPage(false, false, true);
      page.openEditApsData();
    });
    //保存排产数据
    $("#btnSave").on("click", function () {
      page.clearPage(false, false, true);
      page.saveApsData();
    });
    $("#btnClose").on("click", function () {
      $("#dg").dialog("close");
    });
  },
  //初始化页面
  initPage: function () {
    page.post(page.url, { action: "InitPageData" }, true, function (res) {
      if (!res.Result) {
        displayMessage(res.Message, res.Result);
        return;
      }
      $("#txtWorkCenter").combobox({//工区
        valueField: 'WORKCENTERID',
        textField: 'WORKCENTERNAME',
        panelHeight: 200,
        data: res.DBDataSet.dtWorkCenter, //下拉数据
        onSelect: function (record) {
          if (record.WORKCENTERID) {
            page.getTeam(record.WORKCENTERID);
          }
        }
      });
      $("#selAssistFactory").combobox({//承制分厂
        valueField: 'FACTORYID',
        textField: 'FACTORYNAME',
        panelHeight: 200,
        data: res.DBDataSet.dtMainFactory //下拉数据
      });
    });
  },
  //查询
  searchData: function () {
    var params = {
      pageSize: page.pageSize,
      pageNumber: page.pageNumber
    };
    var datas = $("#queryForm").serializeArray();
    $.each(datas, function () {
      params[this.name] = this.value;
    });
    var formData = {
      action: "GetApsPlanShipOutDatas",
      params: JSON.stringify(params)
    };
    page.post(page.url, formData, true, function (res) {
      if (!res.Result) {
        displayMessage(res.Message, res.Result);
        return;
      }
      page.pageTotal = res.RowCount;
      $("#gdApsPlanInfo").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
    });
  },
  // 查询主制单元
  getTeam: function (workcenterid) {
    var mainUrl = getRootPath() + "/Ashx/ProductTeamInfoMaintPageHandler.ashx";//本页面后台路径
    $.ajax({
      type: "post",
      url: mainUrl + "?actions=getTeam",
      data: { action: "getTeam", workcenterid: workcenterid },
      cashe: false,
      dataType: 'json',
      success: function (res) {
        if (res.Result) {
          $("#ddlProductTeam").combobox({
            valueField: 'teamid',
            textField: 'teamname',
            panelHeight: 200,
            data: res.DBTable
          });
        }
      }
    });
  },
  //保存转出
  saveOut: function () {
    page.disableBtn();
    var selected = $("#gdApsPlanInfo").datagrid("getChecked");
    if (selected.length === 0) {
      page.enableBtn();
      displayMessage("请选择数据", false);
      return false;
    }
    var datas = selected.map(function (item) {
      return {
        apsPlanDetailId: item.APSPLANDETAILID,
        containerId: item.CONTAINERID,
        containerName: item.CONTAINERNAME,
        workflowstepId: item.WORKFLOWSTEPID,
        workflowstepName: item.WORKFLOWSTEPNAME,
        specNo: item.SPECNO,
        assisFactoryName: item.ASSISFACTORYNAME,
        specfactoryid: item.SPECFACTORYID
      }
    });
    var formData = {
      action: "ApsPlanShipConfirmVaild",
      datas: JSON.stringify(datas)
    };
    //验证转出
    page.post(page.url, formData, true, function (res) {
      if (res.Result) {
        if (res.ReturnData) {
          $.messager.confirm('确认', '存在其他版本的转工排产数据，是否覆盖？', function (r) {
            if (r) {
              page.postOutData(datas);
            } else {
              page.enableBtn();
            }
          });
        } else {
          page.searchData();
          page.enableBtn();
          displayMessage(res.Message, res.Result);
        }
      } else {
        page.enableBtn();
        displayMessage(res.Message, res.Result);
      }
    });
  },
  postOutData: function (datas) {
    var formData = {
      action: "SaveApsPlanShipConfirmDatas",
      datas: JSON.stringify(datas)
    };
    //验证转出
    page.post(page.url, formData, true, function (res) {
      if (res.Result) {
        page.searchData();
      }
      page.enableBtn();
      displayMessage(res.Message, res.Result);
    });
  },
  //保存调整
  saveReceive: function () {
    $("#btnReceive").linkbutton('disable');
    var selected = $("#gdApsPlanInfo").datagrid("getChecked");
    if (selected.length === 0) {
      displayMessage2("请选择数据", false, ["btnReceive"]);
      return;
    }
    $.messager.confirm('确认', "是否确认调整？", function (r) {
      if (r) {
        var formData = {
          action: "SaveApsPlanShipReceiveDatas",
          type: 0,
          params: JSON.stringify(selected)
        };
        page.post(page.url, formData, true, function (res) {
          if (res.Result) {
            page.searchData();
          }
          displayMessage2(res.Message, res.Result, ["btnReceive"]);
        });
      }
    });
  },
  //编辑排产数据
  openEditApsData: function () {
    page.apsPlanDetailDatas = [];
    var rows = $("#gdApsPlanInfo").datagrid('getChecked');
    if (rows.length === 0) {
      displayMessage("请选择数据", false);
      return;
    }
    //重构页面勾选的数据
    page.apsPlanDetailDatas = rows.map(function (item) {
      return {
        apsplandetailid: item.APSPLANDETAILID,
        containerName: item.CONTAINERNAME
      }
    });
    if (rows.length === 1) {
      if (rows[0].STARTTIME != null) {
        $("#txtStartDate").datetimebox("setValue", dayjs(rows[0].STARTTIME).format('YYYY-MM-DD HH:mm:ss'));
      }
      if (rows[0].ENDTIME != null) {
        $("#txtEndDate").datetimebox("setValue", dayjs(rows[0].ENDTIME).format('YYYY-MM-DD HH:mm:ss'));
      }
    }
    //打开弹窗
    $("#dg").dialog({
      onClose: function () { //关闭事件，恢复主页面按钮
        $("#mainDiv").find(".easyui-linkbutton").each(function () {
          $(this).linkbutton('enable');
        });
      }
    });
    //禁用主页面所有按钮
    $("#mainDiv").find(".easyui-linkbutton").each(function () {
      $(this).linkbutton('disable');
    });
  },
  //保存排产数据
  saveApsData: function () {
    var isValid = $("#ff").form('validate');
    if (!isValid) {
      displayMessage("请填写完整数据", false);
      return false;
    }
    var formData = $("#ff").serializeArray();
    var param = {}
    $.each(formData, function () {
      param[this.name] = this.value;
    });
    var postData = {
      action: "SaveApsPlanDetailData",
      apsPlanDetailDatas: JSON.stringify(page.apsPlanDetailDatas),
      param: JSON.stringify(param)
    };
    //保存
    page.post(page.url, postData, true, function (res) {
      if (res.Result) {
        $("#dg").dialog("close");
        page.searchData();
      }
      displayMessage(res.Message, res.Result);
    })
  },
  //禁用页面按钮
  disableBtn: function () {
    $("body").find(".easyui-linkbutton").each(function () {
      $(this).linkbutton('disable');
    });
  },
  //启用页面按钮
  enableBtn: function () {
    $("body").find(".easyui-linkbutton").each(function () {
      $(this).linkbutton('enable');
    });
  },
  //清除页面（查询区域，列表区域，填写区域，是否清空消息）
  clearPage: function (query, list, msg) {
    if (query) {
      $("#queryForm").find(".easyui-textbox").each(function () {
        $(this).textbox("clear");
      });
      $("#queryForm").find(".easyui-datebox").each(function () {
        $(this).datebox("clear");
      });
      $("#selStatus").combobox("setValue", "0");
      $("#txtWorkCenter").combobox("clear");
      $("#selAssistFactory").combobox("clear");
      $("#selApsType").combobox("setValue", "");
      $("#ddlProductTeam").combobox("setValue", "");
    }
    if (list) {
      clearEasyuiDataGrid("gdApsPlanInfo"); //清空列表
    }
    if (msg) {
      clearMessage();
    }
  },
  //post数据（路径，参数，是否异步，成功返回方法）
  post: function (url, param, async, callback) {
    $.ajax({
      type: "Post",
      url: url,
      data: param,
      cashe: false,
      async: async,
      dataType: "json",
      beforeSend: function () {
        $.messager.progress({ text: '', msg: '处理中...' });
      },
      success: function (data) {
        $.messager.progress('close');
        callback(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.messager.progress('close');
        displayMessage(XMLHttpRequest.responseText, false);
        page.enableBtn();
      }
    });
  }
}
$(function () {
  page.init();
});